<?php

namespace app\admin\controller\order;

use app\admin\model\bin\History;
use app\admin\model\Organization;
use app\admin\model\Bin;
use app\admin\model\bin\Rent as BinRent;
use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 出租订单
 *
 * @icon fa fa-circle-o
 */
class Rent extends Backend
{

    /**
     * Rent模型对象
     * @var \app\admin\model\order\Rent
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\order\Rent;
        $this->view->assign("binTypeList", $this->model->getBinTypeList());
        $this->view->assign("binNativeList", $this->model->getBinNativeList());
        $this->view->assign("binOriginList", $this->model->getBinOriginList());
        $this->view->assign("currencyTypeList", $this->model->getCurrencyTypeList());
        $this->view->assign("yardList", $this->model->yardList());
    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            $pathinfo=input('server.PATH_INFO');
            $bin_origin=1;
            if($pathinfo=='/order/rent/index/bin_origin/1'){
                $bin_origin=1;
            }elseif ($pathinfo=='/order/rent/index/bin_origin/2'){
                $bin_origin=2;
            }
            $this->assign("bin_origin",$bin_origin);

            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams(null,true);
        $list = $this->model
            ->with([
                'type'=>function($query){$query->withField('name');},
                'native'=>function($query){$query->withField('name');},
                'customer'=>function($query){$query->withField('organ_name');},
                'takeyard'=>function($query){$query->withField('organ_name');},
                'returnyard'=>function($query){$query->withField('organ_name');},
                'admin'=>function($query){$query->withField('nickname');},
            ])
            ->where($where)
            ->order(['createtime'=>'desc'])
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     *租箱出库
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            /*            $yardList=Organization::getYard();*/
            $pathinfo=input('server.PATH_INFO');
            $bin_origin=1;
            if($pathinfo=='/order/rent/add/bin_origin/1'){
                $bin_origin=1;
            }elseif ($pathinfo=='/order/rent/add/bin_origin/2'){
                $bin_origin=2;
            }
            $this->assign("bin_origin",$bin_origin);

            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $params['createtime']=time();

        $params['renttime']=strtotime($params['renttime']);
        $params['deadlinetime']=strtotime($params['deadlinetime']);
        $params['rent_sn']='R'.substr(md5(microtime(true)), 0, 9);

        $binIds=[];
        $binHistoty=[];
        $binData=[];
        if(!empty($params['multiplejson'])){
            $binData=$params['multiplejson'];
            unset($params['multiplejson']);
        }
        $params['complete_number']=count($binData);
        if($params['complete_number']==$params['rent_number']){
            $params['is_finish']=1;
        }elseif ($params['complete_number']>$params['rent_number']){
            $this->error('箱子数量已超过计划数量!');
        }

        unset($params['choose_bin']);
        $bin=new Bin();
        $result = false;
        Db::startTrans();
        try {

            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->insertGetId($params);

           /* foreach ($binIds as $item){
               $result= $bin->save([
                    'current_status'  => 3,
                ],['id' => $item]);
            }*/
            if(!empty($binData)) {

                foreach ($binData as $k => &$vo) {
                    $vo = array_merge($params, $vo);
                    $vo['bin_sn'] = $bin->where(['id' => $vo['bin_id']])->value('bin_sn');
                    $vo['rent_order_id'] = $result;
                    if (!empty($vo['take_null_time'])) {
                        $vo['take_null_time'] = strtotime($vo['take_null_time']);
                        $binHistoty[$k]['take_null_time'] = $vo['take_null_time'];
                    }
                    $binIds[$k]['id'] = $vo['bin_id'];
                    $binIds[$k]['current_status'] = 3;
                    $binIds[$k]['last_status'] = 3;

                    $binHistoty[$k]['bin_id'] = $vo['bin_id'];
                    $binHistoty[$k]['business_type'] = 3;
                    $binHistoty[$k]['receipt'] = $vo['rent_sn'];
                    $binHistoty[$k]['organization_id'] = $vo['customer_id'];
                    $binHistoty[$k]['organ_type'] = 4;
                    $binHistoty[$k]['yard_id'] = $vo['take_yard_id'];
                    $binHistoty[$k]['createtime'] = time();
                }
                $binRent = new BinRent();
                $res = $binRent->allowField(true)->saveAll($binData);
                $result = $bin->allowField(true)->isUpdate()->saveAll($binIds);
                $history = new History();
                $historyRes = $history->allowField(true)->saveAll($binHistoty);
            }

            Db::commit();

        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /*
 *    添加箱子
 */

    public function add_bin($ids = null){
        $row = $this->model->get($ids);
        $bin_origin= input('bin_origin');
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        $row= $row->toArray();
        $row['remain_number']=$row['rent_number']-$row['complete_number'];
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $binData=$params['multiplejson'];
        $bin=new Bin();
        $result = false;
        Db::startTrans();
        try {

            if(!empty($binData)) {

                foreach ($binData as $k => &$vo) {
                    $vo['bin_sn'] = $bin->where(['id' => $vo['bin_id']])->value('bin_sn');
                    $vo['rent_order_id'] = $ids;
                    if (!empty($vo['take_null_time'])) {
                        $vo['take_null_time'] = strtotime($vo['take_null_time']);
                        $binHistoty[$k]['take_null_time'] = $vo['take_null_time'];
                    }
                    $vo['customer_id']=$row['customer_id'];
                    $vo['bin_type']=$row['bin_type'];
                    $vo['take_yard_id']=$params['take_yard_id'];
                    $vo['deadlinetime']=$row['deadlinetime'];
                    $vo['tenancy']=$row['tenancy'];
                    $vo['overdue_fee']=$row['overdue_fee'];
                    $vo['salesman_id']=$row['salesman_id'];
                    $vo['unit_price']=$row['unit_price'];
                    $vo['currency_type']=$row['currency_type'];
                    $vo['return_city']=$row['return_city'];
                    $vo['bin_native']=$row['bin_native'];
                    $vo['bin_origin']=$row['bin_origin'];
                    $vo['renttime']=$vo['take_null_time'];
                    $vo['weigh']='';
                    $binIds[$k]['id'] = $vo['bin_id'];
                    $binIds[$k]['current_status'] = 3;
                    $binIds[$k]['last_status'] = 3;

                    $binHistoty[$k]['bin_id'] = $vo['bin_id'];
                    $binHistoty[$k]['business_type'] = 3;
                    $binHistoty[$k]['receipt'] = $row['rent_sn'];
                    $binHistoty[$k]['organization_id'] = $row['customer_id'];
                    $binHistoty[$k]['organ_type'] = 4;
                    $binHistoty[$k]['yard_id'] = $params['take_yard_id'];
                    $binHistoty[$k]['createtime'] = time();
                }
                $binRent = new BinRent();
                $res = $binRent->allowField(true)->saveAll($binData);
                $result = $bin->allowField(true)->isUpdate()->saveAll($binIds);
                $history = new History();
                $historyRes = $history->allowField(true)->saveAll($binHistoty);
                $changeParam=[];
                $changeParam['complete_number']=$row['complete_number']+count($binData);
                if($changeParam['complete_number']==$row['rent_number']){
                    $changeParam['is_finish']=1;
                } elseif ($changeParam['complete_number']>$row['rent_number']){
                    $this->error('箱子数量已超过计划数量!');
                }

                $result = $this->model->allowField(true)->save($changeParam,['id'=>$ids]);

            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();

    }

}
